package com.wenzhoujie.fragment;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.wenzhoujie.library.utils.SDToast;
import com.lidroid.xutils.http.ResponseInfo;
import com.lingou.www.R;
import com.sunday.eventbus.SDBaseEvent;
import com.wenzhoujie.HomeMoreCategoryActivity;
import com.wenzhoujie.MyCaptureActivity;
import com.wenzhoujie.WebViewActivity;
import com.wenzhoujie.adapter.HomeIndexAdapter;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.common.CommonInterface;
import com.wenzhoujie.customview.SDGridViewInScroll;
import com.wenzhoujie.event.EnumEventTag;
import com.wenzhoujie.listener.RequestScanResultListener;
import com.wenzhoujie.model.IndexActIndexsModel;
import com.wenzhoujie.model.LocalUserModel;
import com.wenzhoujie.model.Mobile_qrcodeActModel;
import com.wenzhoujie.model.act.IndexActNewModel;
import com.wenzhoujie.utils.IocUtil;
import com.wenzhoujie.utils.SDCollectionUtil;
import com.wenzhoujie.utils.SDTypeParseUtil;
import com.wenzhoujie.utils.ViewInject;

/**
 * 首页分类fragment
 * 
 * @author js02
 * 
 */
public class HomeIndexFragment extends BaseFragment
{

	private static final int HOME_INDEX_NUMBER = 8;

	public static final int REQUEST_CODE_SCAN_CODE = 1;

	@ViewInject(id = R.id.frag_home_index_ll_all)
	private LinearLayout mLlAll = null;

	@ViewInject(id = R.id.frag_home_index_gv_cates)
	private SDGridViewInScroll mGvCates = null;

	private IndexActNewModel mIndexModel = null;
	private List<IndexActIndexsModel> mListModel = new ArrayList<IndexActIndexsModel>();

	private HomeIndexAdapter mAdapter = null;

	private boolean mIsScanActivityStartByThis = false;

	public void setmIndexModel(IndexActNewModel indexModel)
	{
		this.mIndexModel = indexModel;
		this.mListModel = mIndexModel.getIndexs();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.frag_home_index, container, false);
		IocUtil.initInjectedView(this, view);
		init();
		return view;
	}

	private void init()
	{
		bindDefaultData();
		bindData();
	}

	private void bindData()
	{
		if (mListModel != null && mListModel.size() > 0)
		{
			mLlAll.setVisibility(View.VISIBLE);
			List<IndexActIndexsModel> listModel = null;
			if (mListModel.size() >= HOME_INDEX_NUMBER) // 如果超过8项，截取8项展示
			{
				listModel = SDCollectionUtil.subListToSize(mListModel, HOME_INDEX_NUMBER);
				IndexActIndexsModel lastModel = listModel.get(HOME_INDEX_NUMBER - 1); // 把第8项的名字改为更多
				if (lastModel != null)
				{
					lastModel.setTempName("更多");
				}
			} else
			{//如果没有超过8项,就直接显示菜单
				listModel = mListModel;
			}
			if (mAdapter != null)
			{ //使用函数来将列表模型数据绑定到视图中
				mAdapter.updateListViewData(listModel);
			}
		} else
		{//如果没有获取到菜单就不显示视图
			mLlAll.setVisibility(View.GONE);
		}
	}

	private void bindDefaultData()
	{
		mAdapter = new HomeIndexAdapter(mListModel, getActivity());
		mGvCates.setAdapter(mAdapter);
		mGvCates.setOnItemClickListener(new OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id)
			{
				if (id == (HOME_INDEX_NUMBER - 1)) // 更多被点击
				{
					mAdapter.getItem((int) id).restoreOriginalName();
					// TODO 跳转到全部分类界面
					Intent intent = new Intent(App.getApplication(), HomeMoreCategoryActivity.class);
					intent.putExtra(HomeMoreCategoryActivity.EXTRA_INITACTCITYLISTMODEL, (Serializable) mListModel);//mIndexModel)mListModel;
					startActivity(intent);
				}
				/*else if (id == (HOME_INDEX_NUMBER - 2)) //外卖宵夜
				{
					IndexActIndexsModel model = mAdapter.getItem((int) id);
					String theUrl = model.getData().getUrl();
					LocalUserModel userModel = App.getApplication().getmLocalUser();
					
					
					 * 首页的“外卖宵夜”接口地址和个人中心页的“我的餐车”地址，都加上un和uid参数，
					 * 如果用户是登录状态这两个参数值就分别是用户名和用户id，
					 * 如果不是登陆状态这两个参数值就是空。
					 
					
					String uname = "";
					String upw = "";
					if(userModel!=null)
					{
						uname =  userModel.getUser_name();
						//userModel.getUser_id();
						//upass = userModel.getUser_pwd();
						upw = userModel.getUser_pwd();
					}
					String url2 = "";
					//theUrl = theUrl + "&from=app&un="+uname+"&upw="+upw;
					url2 = theUrl + "&from=app&un="+uname+"&upw="+upw;
					//String url3 = "http://test.wenzhoujie.com/dc/index.php?m=wap&from=app%un=aaa&upw=111111";
					//System.out.println("订餐的DCURL2: "+url2);
					
					Intent intent = new Intent(App.getApplication(), WebViewActivity.class);
					intent.putExtra(WebViewActivity.EXTRA_URL, url2);
					startActivity(intent);
					
					//SDToast.showToast("订餐的DCURL2: "+url2);
				}*/
				else 
				{
					IndexActIndexsModel model = mAdapter.getItem((int) id);
					clickIndex(model);
				}
			}
		});
	}

	public static String md5(String string) {
	    byte[] hash;
	    try {
	        hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
	    } catch (NoSuchAlgorithmException e) {
	        throw new RuntimeException("MD5 should be supported?", e);
	    } catch (UnsupportedEncodingException e) {
	        throw new RuntimeException("UTF-8 should be supported?", e);
	    }

	    StringBuilder hex = new StringBuilder(hash.length * 2);
	    for (byte b : hash) {
	        if ((b & 0xFF) < 0x10) hex.append("0");
	        hex.append(Integer.toHexString(b & 0xFF));
	    }
	    return hex.toString();
	}
	
	/**
	 * 分类被点击
	 * 
	 * @param model
	 */
	protected void clickIndex(IndexActIndexsModel model)
	{
		if (model != null)
		{
			int type = SDTypeParseUtil.getIntFromString(model.getType(), -1);
			Intent intent = IndexActNewModel.createIntentByType(type, model.getData(), true); //点击事件,这个写在了控制里面
			if (intent != null)
			{
				try
				{System.out.println("type:"+Integer.toString(type));
					if (type == 25) // 扫一扫
					{
						mIsScanActivityStartByThis = true;
						startActivityForResult(intent, REQUEST_CODE_SCAN_CODE); //需要返回的调用
					} else
					{
						startActivity(intent);
					}
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 处理扫描结果
	 * 
	 * @param scanResult
	 */
	private void requestScanResult(String scanResult)
	{
		if (AppHelper.isEmptyString(scanResult))
		{
			SDToast.showToast("扫描结果为空");
			return;
		}

		CommonInterface.requestScanResult(scanResult, new RequestScanResultListener()
		{
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo, Mobile_qrcodeActModel model)
			{
				int type = model.getTypeFormat();
				if (type == 0) // 未解释成功
				{
					SDToast.showToast("对不起，解释二维码失败");
				} else
				{
					Intent intent = IndexActNewModel.createIntentByType(type, model.getData(), false);
					if (intent != null)
					{
						try
						{
							startActivity(intent);
						} catch (Exception e)
						{
							e.printStackTrace();
						}
					} else
					{
						SDToast.showToast("未知的类型：" + type);
					}
				}
			}

			@Override
			public void onStart()
			{
				AppHelper.showLoadingDialog("正在解释验证码");
			}

			@Override
			public void onFinish()
			{
				AppHelper.hideLoadingDialog();
			}

			@Override
			public void onFailure()
			{
				SDToast.showToast("解释失败");
			}
		});
	}

	@Override
	public void onEventMainThread(SDBaseEvent event)
	{
		// TODO Auto-generated method stub
		super.onEventMainThread(event);
		switch (EnumEventTag.valueOf(event.getEventTagInt()))
		{
		case SCAN_CODE_SUCCESS:
			if (mIsScanActivityStartByThis)
			{
				mIsScanActivityStartByThis = false;
				Intent intent = (Intent) event.getEventData();
				String scanResult = intent.getStringExtra(MyCaptureActivity.EXTRA_RESULT_SUCCESS_STRING);
				requestScanResult(scanResult);
			}
			break;

		default:
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
		case REQUEST_CODE_SCAN_CODE:
			if (resultCode == MyCaptureActivity.RESULT_CODE_SCAN_SUCCESS)
			{
				String scanResult = data.getStringExtra(MyCaptureActivity.EXTRA_RESULT_SUCCESS_STRING);
				requestScanResult(scanResult);
			}
			break;

		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}